import javax.swing.*;
import java.awt.*;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;

public class GamePanel extends JPanel implements Runnable {
    private static final int WIDTH = 800;
    private static final int HEIGHT = 500;
    private static final int DELAY = 16; // 约60FPS

    private Thread gameThread;
    private boolean isRunning;
    private boolean isPaused;

    private Player player;
    private List<Enemy> enemies;
    private List<Bullet> bullets;
    private List<Explosion> explosions;
    private Random random;
    private GameMain gameMain;
    private int score;
    private int level;
    private long lastEnemySpawnTime;
    private long enemySpawnInterval;

    public GamePanel(GameMain gameMain) {
        this.gameMain = gameMain;
        setPreferredSize(new Dimension(WIDTH, HEIGHT));
        setBackground(Color.BLACK);
        setFocusable(true);

        random = new Random();
        initGame();
    }

    private void initGame() {
        player = new Player(WIDTH / 2, HEIGHT - 80);
        player.setGamePanel(this);
        enemies = new ArrayList<>();
        bullets = new ArrayList<>();
        explosions = new ArrayList<>();
        score = 0;
        level = 1;
        lastEnemySpawnTime = System.currentTimeMillis();
        enemySpawnInterval = 1000; // 初始生成间隔为1秒
        spawnEnemies();
    }

    private void spawnEnemies() {
        enemies.clear();
        for (int i = 0; i < 5 + level; i++) {
            int x = random.nextInt(WIDTH - 60);
            int y = random.nextInt(100) - 200; // 从屏幕外开始
            enemies.add(new Enemy(x, y, level));
        }
    }

    public void startGame() {
        if (gameThread == null || !isRunning) {
            isRunning = true;
            isPaused = false;
            gameThread = new Thread(this);
            gameThread.start();
        } else if (isPaused) {
            isPaused = false;
        }
    }

    public void pauseGame() {
        isPaused = !isPaused;
    }

    public boolean isPaused() {
        return isPaused;
    }

    public void resetGame() {
        isRunning = false;
        if (gameThread != null) {
            try {
                gameThread.join();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        initGame();
        repaint();
    }

    @Override
    public void run() {
        long lastTime = System.nanoTime();
        double nsPerTick = 1000000000D / 60D; // 60 FPS

        int frames = 0;
        int ticks = 0;
        long lastTimer = System.currentTimeMillis();

        double delta = 0;

        while (isRunning) {
            long now = System.nanoTime();
            delta += (now - lastTime) / nsPerTick;
            lastTime = now;

            boolean shouldRender = true;

            while (delta >= 1) {
                ticks++;
                if (!isPaused) {
                    update();
                }
                delta -= 1;
                shouldRender = true;
            }

            try {
                Thread.sleep(2);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

            if (shouldRender) {
                frames++;
                repaint();
            }

            if (System.currentTimeMillis() - lastTimer >= 1000) {
                lastTimer += 1000;
                frames = 0;
                ticks = 0;
            }
        }
    }

    private void update() {
        // 更新玩家
        player.update();

        // 更新子弹
        for (int i = 0; i < bullets.size(); i++) {
            Bullet bullet = bullets.get(i);
            bullet.update();
            if (bullet.getY() < 0) {
                bullets.remove(i);
                i--;
            }
        }

        // 更新敌人
        long currentTime = System.currentTimeMillis();
        if (currentTime - lastEnemySpawnTime > enemySpawnInterval) {
            int x = random.nextInt(WIDTH - 60);
            enemies.add(new Enemy(x, -50, level)); // 从屏幕顶部外生成
            lastEnemySpawnTime = currentTime;

            // 随着时间减少生成间隔，增加难度
            if (enemySpawnInterval > 300) {
                enemySpawnInterval -= 5;
            }
        }

        for (int i = 0; i < enemies.size(); i++) {
            Enemy enemy = enemies.get(i);
            enemy.update();

            // 检查敌人是否离开屏幕
            if (enemy.getY() > HEIGHT) {
                enemies.remove(i);
                i--;
                continue;
            }

            // 检查敌人是否被子弹击中
            boolean enemyHit = false;
            for (int j = 0; j < bullets.size(); j++) {
                Bullet bullet = bullets.get(j);
                if (bullet.getBounds().intersects(enemy.getBounds())) {
                    enemies.remove(i);
                    bullets.remove(j);
                    i--;
                    j--;
                    score += enemy.getPoints();
                    gameMain.updateScore(score);

                    // 添加爆炸效果
                    explosions.add(new Explosion(enemy.getX(), enemy.getY()));

                    // 每100分升一级
                    if (score % 100 == 0 && score > 0) {
                        levelUp();
                    }

                    enemyHit = true;
                    break;
                }
            }

            if (enemyHit) continue;

            // 检查敌人是否与玩家碰撞
            if (enemy.getBounds().intersects(player.getBounds())) {
                isRunning = false;
                explosions.add(new Explosion(player.getX(), player.getY()));
                JOptionPane.showMessageDialog(this, "游戏结束！最终得分: " + score, "游戏结束", JOptionPane.INFORMATION_MESSAGE);
                SwingUtilities.invokeLater(new Runnable() {
                    @Override
                    public void run() {
                        resetGame();
                        gameMain.startButton.setEnabled(true);
                        gameMain.pauseButton.setText("暂停游戏");
                        gameMain.pauseButton.setEnabled(false);
                        gameMain.resetButton.setEnabled(false);
                    }
                });
                return;
            }
        }

        // 更新爆炸效果
        for (int i = 0; i < explosions.size(); i++) {
            Explosion explosion = explosions.get(i);
            explosion.update();
            if (explosion.isFinished()) {
                explosions.remove(i);
                i--;
            }
        }
    }

    private void levelUp() {
        level++;
        enemySpawnInterval = Math.max(300, enemySpawnInterval - 100); // 减少生成间隔
        JOptionPane.showMessageDialog(this, "恭喜升级！当前等级: " + level, "升级", JOptionPane.INFORMATION_MESSAGE);
    }

    @Override
    protected void paintComponent(Graphics g) {
        super.paintComponent(g);
        Graphics2D g2d = (Graphics2D) g;

        // 抗锯齿
        g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
        g2d.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON);

        // 绘制渐变背景
        GradientPaint gp = new GradientPaint(0, 0, Color.BLACK, 0, HEIGHT, new Color(0, 0, 50));
        g2d.setPaint(gp);
        g2d.fillRect(0, 0, WIDTH, HEIGHT);

        // 绘制星星背景
        g2d.setColor(Color.WHITE);
        for (int i = 0; i < 100; i++) {
            int starSize = random.nextInt(2) + 1;
            g2d.fillRect(random.nextInt(WIDTH), random.nextInt(HEIGHT), starSize, starSize);
        }

        // 绘制玩家
        player.draw(g2d);

        // 绘制子弹
        for (Bullet bullet : bullets) {
            bullet.draw(g2d);
        }

        // 绘制敌人
        for (Enemy enemy : enemies) {
            enemy.draw(g2d);
        }

        // 绘制爆炸效果
        for (Explosion explosion : explosions) {
            explosion.draw(g2d);
        }

        // 绘制游戏信息
        g2d.setColor(Color.WHITE);
        g2d.setFont(new Font("Arial", Font.BOLD, 16));
        g2d.drawString("分数: " + score, 20, 30);
        g2d.drawString("等级: " + level, 20, 60);

        // 如果游戏暂停，显示暂停信息
        if (isPaused) {
            g2d.setColor(new Color(255, 255, 255, 180));
            g2d.setFont(new Font("Arial", Font.BOLD, 40));
            FontMetrics fm = g2d.getFontMetrics();
            String pauseText = "游戏暂停";
            g2d.drawString(pauseText, (WIDTH - fm.stringWidth(pauseText)) / 2, HEIGHT / 2);

            g2d.setFont(new Font("Arial", Font.PLAIN, 20));
            String continueText = "按继续按钮继续游戏";
            fm = g2d.getFontMetrics();
            g2d.drawString(continueText, (WIDTH - fm.stringWidth(continueText)) / 2, HEIGHT / 2 + 50);
        }

        g2d.dispose();
    }

    public void shoot() {
        if (!isPaused && isRunning) {
            bullets.add(new Bullet(player.getX() + player.getWidth() / 2 - 2, player.getY()));
        }
    }
}    